package com.quanthium.monitor.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import com.quanthium.monitor.dingtalk.CustomDingTalkNotifier;

import de.codecentric.boot.admin.server.config.AdminServerNotifierAutoConfiguration.DingTalkNotifierConfiguration;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
import de.codecentric.boot.admin.server.notify.DingTalkNotifier;
import de.codecentric.boot.admin.server.notify.NotifierProxyProperties;

@Configuration
@AutoConfigureBefore(DingTalkNotifierConfiguration.class)
public class MonitorConfiguration {
	private static RestTemplate createNotifierRestTemplate(NotifierProxyProperties proxyProperties) {
		RestTemplate restTemplate = new RestTemplate();
		if (proxyProperties.getHost() != null) {
			HttpClientBuilder builder = HttpClientBuilder.create();
			builder.setProxy(new HttpHost(proxyProperties.getHost(), proxyProperties.getPort()));

			if (proxyProperties.getUsername() != null && proxyProperties.getPassword() != null) {
				CredentialsProvider credsProvider = new BasicCredentialsProvider();
				credsProvider.setCredentials(new AuthScope(proxyProperties.getHost(), proxyProperties.getPort()),
						new UsernamePasswordCredentials(proxyProperties.getUsername(), proxyProperties.getPassword()));
				builder.setDefaultCredentialsProvider(credsProvider);
			}

			restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(builder.build()));
		}
		return restTemplate;
	}

	@Bean
	@ConfigurationProperties("spring.boot.admin.notify.dingtalk")
	DingTalkNotifier dingTalkNotifier(InstanceRepository repository, NotifierProxyProperties proxyProperties) {
		return new CustomDingTalkNotifier(repository, createNotifierRestTemplate(proxyProperties));
	}
}
